// #ifdef H5
var jweixin = require("@/static/h5/js/jssdk.js");
// #endif
import allrequest from "api/allrequest.js";

// 需要使用的JS接口列表
let jsApiList = [
  "checkJsApi",
  "getLocation",
  "chooseWXPay",
  "onMenuShareAppMessage",
  "onMenuShareTimeline"
];
let openTagList = ["wx-open-launch-weapp", "wx-open-subscribe"];

export default {
  // 配置信息
  initJssdk: async () => {
    // 页面 url
    // console.log("url,", window.location.href);

    uni.getSystemInfo({
      success: async (r) => {
        let url = window.location.href;

        // ios 平团不可以传 # 号，否则需要刷新页面才可以注入成功
        if (
          r.errMsg === "getSystemInfo:ok" &&
          r.platform.toLowerCase() === "ios"
        ) {
          url = url.split("#")[0];
        }

  
        const res = await allrequest.request.jsConfig({
          url: url,
          api: [
            "checkJsApi",
            "getLocation",
            "chooseWXPay",
            "onMenuShareAppMessage",
            "onMenuShareTimeline"
          ]
        });
        console.log("res,", res);

        if (res.code == 0) {
          jweixin.config({
            debug: false,
            appId: res.data.appId,
            timestamp: res.data.timestamp,
            nonceStr: res.data.nonceStr,
            signature: res.data.signature,
            jsApiList,
            openTagList
          });
          jweixin.ready(() => {
            const shareData = JSON.parse(
              JSON.stringify(uni.getStorageSync("share_obj"))
            );

            shareData.link = shareData.path;
            delete shareData.path;

            jweixin.onMenuShareAppMessage({
              ...shareData,
              success: () => {
                console.log(shareData, "shareData");
              },
              fail: (err) => {
                uni.$u.toast(err);
              }
            });

            jweixin.onMenuShareTimeline({
              ...shareData,
              success: () => {
                console.log(shareData, "shareData");
              },
              fail: (err) => {
                uni.$u.toast(err);
              }
            });
          });
        }
        return;
      }
    });
  },

  // 检查权限
  checkJsApi: function (_option = {}) {
    jweixin.checkJsApi({
      jsApiList
    });
  },
  // 获取位置信息
  getLocation: function () {
    jweixin.getLocation({
      type: "wgs84"
    });
  },
  // 支付
  jsPay(params, cb) {
    jweixin.chooseWXPay({
      timestamp: params.timestamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
      nonceStr: params.nonceStr, // 支付签名随机串，不长于 32 位
      package: params.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
      signType: params.signType, // 微信支付V3的传入RSA,微信支付V2的传入格式与V2统一下单的签名格式保持一致
      paySign: params.paySign, // 支付签名
      success(res) {
        // 支付成功后的回调函数
        cb(res);
      }
    });
  }
};
